﻿using _9jCardRegisterCollection.Models;
using _9jCardRegisterCollection.Views;
using AntdUI;
using CardRegisterCollection.Model;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace _9jCardRegisterCollection
{
    public partial class FrmMain : AntdUI.Window
    {
        private UserControl _control;
        public static Dictionary<string, List<ShowMenu>> ShowMenus = new Dictionary<string, List<ShowMenu>>();
        public FrmMain()
        {
            InitializeComponent();
            //加载配置文件
            LoadAppConfig();
            //加载菜单
            LoadMenu();
            //绑定事件
            BindEventHandler();
        }

        private void BindEventHandler()
        {
            menu.SelectChanged += Menu_SelectChanged;
        }

        private void Menu_SelectChanged(object sender, MenuSelectEventArgs e)
        {
            var name = e.Value.Tag;
            //if (control != null)
            //{
            //    if (control is FloatButtonDemo floatButtonDemo)
            //    {
            //        floatButtonDemo.CloseFloatButtonForm(); // 清理浮动按钮窗体
            //    }
            //    control?.Dispose();
            //    control = null;
            //}
            panel_content.Controls.Clear();
            switch (name)
            {
                case "DomesticPersonnel":
                    _control = new DomesticAttendeePage(this);
                    break;
                case "OverseasPersonnel":
                    _control = new OverseasAttendeePage(this);
                    break;
                case "CarManagement":
                    _control = new CarPage(this);
                    break;
                case "UnitManagement":
                    _control = new UnitManagementPage(this);
                    break;
                case "UserManagement":
                    _control = new UserManagementPage(this);
                    break;
                case "RoleManagement":
                    _control = new RoleManagementPage(this);
                    break;
                case "CardTypeManagement":
                    _control = new CardTypeManagementPage(this);
                    break;
                case "ConfigurationShare":
                    _control = new ConfigurationSharePage();
                    break;
                default:
                    break;
            }
            if (_control != null)
            {
                //容器添加控件，需要调整dpi
                _control.Dock = DockStyle.Fill;
                AutoDpi(_control);
                panel_content.Controls.Add(_control);
            }
        }

        private void LoadMenu(string filter = "")
        {

            menu.Items.Clear();
            ShowMenus.Clear();
            List<MenuItems> menuItems = new List<MenuItems>();
            var menus = CurrentLoginInfo.Menus;
            for (int i = 0; i < menus.Count; i++)
            {
                var menu = menus[i];

                if (menu.ParentId.Equals("0"))
                {
                    string firstMenu = menu.Title;
                    string firstMenuId = menu.ID.ToString();
                    List<ShowMenu> showMenu = new List<ShowMenu>();
                    for (int j = 0; j < menus.Count; j++)
                    {
                        if (i == j) { continue; }
                        if (menus[j].ParentId.Equals(firstMenuId))
                        {
                            ShowMenu item = new ShowMenu();
                            item.Text = menus[j].Title;
                            item.Tag = menus[j].Name;
                            showMenu.Add(item);
                        }
                    }
                    ShowMenus.Add(firstMenu, showMenu);
                }
            }

            //DataSet ds = DbHelperOleDb.Query("SELECT * FROM menu");
            foreach (var rootItem in ShowMenus)
            {
                var rootKey = rootItem.Key.ToLower();
                var rootMenu = new AntdUI.MenuItem { Text = rootItem.Key };
                bool rootVisible = false; // 用于标记是否显示根节点

                foreach (var item in rootItem.Value)
                {
                    var childText = item.Text.ToLower();

                    // 如果子节点包含搜索文本
                    if (childText.Contains(filter))
                    {
                        var menuItem = new AntdUI.MenuItem
                        {
                            Text = item.Text,
                            IconSvg = item.IconSvg,
                            Tag = item.Tag,
                        };
                        rootMenu.Sub.Add(menuItem);
                        rootVisible = true; // 如果有子节点包含，则显示根节点
                    }
                }

                // 如果根节点包含搜索文本，或有可见的子节点，则显示根节点
                if (rootKey.Contains(filter) || rootVisible)
                {
                    menu.Items.Add(rootMenu);
                }
            }

        }

        private void LoadAppConfig()
        {

            //// 读取 appsettings.json 文件
            //var appSettings = AppSetting.GetAppSettings();
            //// 加载色彩模式
            //var value = appSettings["ColorMode"]?.ToString();
            //if (value == "Auto")
            //{
            //    ThemeHelper.SetColorMode(this, ThemeHelper.IsLightMode());
            //}
            //else
            //{
            //    ThemeHelper.SetColorMode(this, value == "Light");
            //}

            //// 加载动画
            //var animation = appSettings["Animation"]?.ToString();
            //AntdUI.Config.Animation = animation == "True";

            //// 加载阴影
            //var shadow = appSettings["ShadowEnabled"]?.ToString();
            //AntdUI.Config.ShadowEnabled = shadow == "True";

            //// 滚动条
            //var scrollbar = appSettings["ScrollBarHide"]?.ToString();
            //AntdUI.Config.ScrollBarHide = scrollbar == "True";

            //// 窗口内弹出 Message/Notification
            //var popup = appSettings["ShowInWindow"]?.ToString();
            //AntdUI.Config.ShowInWindow = popup == "True";

            //// 通知消息边界偏移量XY（Message/Notification）
            //var messageOffset = appSettings["NoticeWindowOffsetXY"]?.ToString();
            //AntdUI.Config.NoticeWindowOffsetXY = Convert.ToInt32(messageOffset);

            this.winBarSystem.SubText = $"{CurrentLoginInfo.UserInfo.UnitName}({CurrentLoginInfo.UserInfo.DeptName})";
            this.butUserAvatar.Text = CurrentLoginInfo.UserInfo.TrueName;
        }


        /// <summary>
        /// 窗体关闭前发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            var rlt = AntdUI.Modal.open(new AntdUI.Modal.Config(this, "系统消息", "确定要退出信息采集注册系统吗？")
            {
                Icon = TType.Info,
                Padding = new Size(24, 20),
            });
            if (rlt != DialogResult.OK)
            {
                e.Cancel = true;
                return;
            }

            icnApp.Visible = false;
        }

        /// <summary>
        /// 单击图标
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void icnApp_Click(object sender, System.EventArgs e)
        {
            var menuStripItems = new AntdUI.IContextMenuStripItem[]
            {
                new AntdUI.ContextMenuStripItem("配置同步", "Ctrl+A")
                {
                    Tag = "config-sync",
                    IconSvg = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"128\" height=\"128\" viewBox=\"0 0 24 24\"><path fill=\"#666666\" d=\"m17 18l-1.4-1.4l4.55-4.6l-4.55-4.6L17 6l6 6zM7 18l-6-6l6-6l1.4 1.4L3.85 12l4.55 4.6zm1-5q-.425 0-.712-.288T7 12t.288-.712T8 11t.713.288T9 12t-.288.713T8 13m4 0q-.425 0-.712-.288T11 12t.288-.712T12 11t.713.288T13 12t-.288.713T12 13m4 0q-.425 0-.712-.288T15 12t.288-.712T16 11t.713.288T17 12t-.288.713T16 13\"/></svg>",
                },
                new AntdUI.ContextMenuStripItem("退出系统", "Ctrl+Q")
                {
                    Tag = "logout",
                    IconSvg = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"128\" height=\"128\" viewBox=\"0 0 24 24\"><path fill=\"none\" stroke=\"#666666\" d=\"M24 12H8m10.5-5c0 .577.665 1.562 1.228 2.294a7.5 7.5 0 0 0 1.745 1.662C22.2 11.445 23.2 12 23.99 12c-.79 0-1.79.556-2.517 1.044a7.5 7.5 0 0 0-1.745 1.662c-.563.732-1.228 1.717-1.228 2.294m-4-10V2.5h-.329A46 46 0 0 1 1.103.605L.75.5H.5v23h.25l.353-.105A46 46 0 0 1 14.171 21.5h.329V17\"/></svg>",
                }
            };
            AntdUI.ContextMenuStrip.open(this, it =>
            {
                switch (it.Tag)
                {
                    case "config-sync":
                        var frmConfigSync = new FrmConfigSync();
                        frmConfigSync.ShowDialog();
                        break;
                    case "logout":
                        this.Close();
                        break;
                }
            }, menuStripItems);
        }

        /// <summary>
        /// 用户头像
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserAvatar_Click(object sender, System.EventArgs e)
        {
            var menuStripItems = new AntdUI.IContextMenuStripItem[]
            {
                new AntdUI.ContextMenuStripItem("密码设置", "Ctrl+P")
                {
                    Tag = "password-setting",
                    IconSvg = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"128\" height=\"128\" viewBox=\"0 0 48 48\"><g fill=\"none\" stroke=\"#666666\" stroke-linejoin=\"round\" stroke-width=\"4\"><path d=\"m24 4l-6 6h-8v8l-6 6l6 6v8h8l6 6l6-6h8v-8l6-6l-6-6v-8h-8z\"/><path d=\"M24 30a6 6 0 1 0 0-12a6 6 0 0 0 0 12Z\"/></g></svg>",
                }
            };
            AntdUI.ContextMenuStrip.open(this, it =>
            {
                switch (it.Tag)
                {
                    case "password-setting":
                        break;
                }
            }, menuStripItems);
        }
    }
}
